$(document).ready(->
  saveBtn = $("#saveBtn")
  nameField = $("#nameField")
  urlField = $("#urlField")
  serverList = $("#serverList")

  opts = Utils.getSetting()


  saveBtn.click(
    ->
      opts.servers.push({
        name: nameField.val()
        url: urlField.val()
      })
      nameField.val("")
      urlField.val("")
      Utils.saveSetting(opts);
      reloadServerLists()
  )

  Utils.bindRadioOpts(opts, "downMode")
  Utils.bindRadioOpts(opts, "notifyMode")
  Utils.bindTextOpts(opts, "yaawURL")

  reloadServerLists = ->
    serverList.find('.server_tr').remove()
    for item in opts.servers
      do (item)->
        enableBox = $("<input type='checkbox'/>");
        enableBox.click(->
          item.select = this.checked
          Utils.saveSetting(opts);
        )
        enableBox.attr("checked", true) if item.select is true
        tr = $("<tr class='server_tr'></tr>")
        $("<td></td>").appendTo(tr).append(enableBox);
        $("<td></td>").appendTo(tr).append("<span>#{item.name}</span>");
        $("<td></td>").appendTo(tr).append("<span>#{item.url}</span>");
        delBtn = $('<a class="btn btn-link" style="margin:0;padding:0">删除</a>')
        delBtn.click(->
          for t,i in opts.servers
            if t is item
              nameField.val(t.name)
              urlField.val(t.url)
              opts.servers.splice(i, 1)
              Utils.saveSetting(opts);
              reloadServerLists()
              return
        )


        yaawBtn = $('<a class="btn btn-link" style="margin:0;padding:0">管理</a>')
        yaawBtn.click(->
          chrome.runtime.sendMessage({
            type :"openYaaw"
            val : item
          })
        )
        $("<td></td>").appendTo(tr).append(delBtn).append(" | ").append(yaawBtn);


        serverList.append(tr)
        return
    return
  reloadServerLists()
);